package com.ohppchuan.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Map;

@RestController
@RequestMapping("/api/devices")
@CrossOrigin(origins = "*") // 允许所有跨域请求
public class DeviceController {

    private final DeviceDataService dataService;

    @Autowired
    public DeviceController(DeviceDataService dataService) {
        this.dataService = dataService;
    }

    @GetMapping("/test")
    public ResponseEntity<String> healthCheck() {
        return ResponseEntity.ok("service is ok.");
    }

    @PostMapping
    public ResponseEntity<Map<String, String>> saveDeviceData(@RequestBody Map<String, Object> payload) {
        String IMEI;
        try {
            Map<String, Object> header = (Map<String, Object>) ((Map<String, Object>) payload.get("notify_data")).get("header");
            IMEI = header.get("node_id").toString();

            // 检查请求体内容并存储到对应Map
            String payloadString = payload.toString();
            if (payloadString.contains("[uploadDATA]")) {
                dataService.saveDeviceData(IMEI, payload, "data");
            } else if (payloadString.contains("GPS")) {
                dataService.saveDeviceData(IMEI, payload, "gps");
            } else {
                System.out.println("[WARNING]: Invalid POST content, missing identifier");
                return ResponseEntity.badRequest().build();
            }
        } catch (Exception e) {
            System.out.println("[WARNING]: Bad POST: " + e.getMessage());
            return ResponseEntity.badRequest().build();
        }

        System.out.println("[INFO]: Add a New Message to IMEI=" + IMEI + " Successfully.");
        return ResponseEntity.ok(Collections.singletonMap("status", "success"));
    }

    @GetMapping
    public ResponseEntity<Map<String, Object>> getDeviceData(
            @RequestParam(value = "imei", required = true) String imei,
            @RequestParam(value = "type", required = true) String type) {
        try {
            Map<String, Object> data = dataService.getDeviceData(imei, type);
            System.out.println("[INFO]: GET " + type.toUpperCase() + " data for IMEI=" + imei + " Successfully.");
            return ResponseEntity.ok(data);
        } catch (IllegalArgumentException e) {
            System.out.println("[WARNING]: Invalid type parameter: " + type);
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            System.out.println("[WARNING]: Data not found for IMEI=" + imei + ", type=" + type);
            return ResponseEntity.notFound().build();
        }
    }
}
